package com.zrwl.poscloud.xo.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zrwl.poscloud.base.entity.*;
import com.zrwl.poscloud.base.enums.EBusiType;
import com.zrwl.poscloud.base.enums.EStatus;
import com.zrwl.poscloud.base.superI.SuperServiceImpl;
import com.zrwl.poscloud.commons.utils.JsonUtils;
import com.zrwl.poscloud.commons.utils.RedisUtil;
import com.zrwl.poscloud.commons.utils.ResultUtil;
import com.zrwl.poscloud.commons.utils.StringUtils;
import com.zrwl.poscloud.xo.global.MessageConf;
import com.zrwl.poscloud.xo.global.RedisConf;
import com.zrwl.poscloud.xo.global.SQLConf;
import com.zrwl.poscloud.xo.global.SysConf;
import com.zrwl.poscloud.xo.mapper.UserEmployeeRMapper;
import com.zrwl.poscloud.xo.service.*;
import com.zrwl.poscloud.xo.vo.EmployeeAccountRecordVO;
import com.zrwl.poscloud.xo.vo.EmployeeVO;
import com.zrwl.poscloud.xo.vo.UserEmployeeRVO;
import com.zrwl.poscloud.xo.vo.UserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 用户关注持卡人员 服务实现类
 *
 * @author 刘思童 AutoGenerate
 * @date 2021-02-24
 */
@Service
public class UserEmployeeRServiceImpl extends SuperServiceImpl<UserEmployeeRMapper, UserEmployeeR> implements UserEmployeeRService {

    @Autowired
    private UserEmployeeRService userEmployeeRService;
    @Autowired
    private UserService userService;
    @Autowired
    private RedisUtil redisUtil;
    @Resource
    private UserEmployeeRMapper userEmployeeRMapper;
    @Autowired
    private EmployeeService employeeService;

    @Override
    public IPage<UserEmployeeR> getPageList(UserEmployeeRVO userEmployeeRVO) {
        QueryWrapper<UserEmployeeR> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(userEmployeeRVO.getKeyword()) && !StringUtils.isEmpty(userEmployeeRVO.getKeyword().trim())) {
            queryWrapper.like("name", userEmployeeRVO.getKeyword().trim());
        }
        Page<UserEmployeeR> page = new Page<>();
        page.setCurrent(userEmployeeRVO.getCurrentPage());
        page.setSize(userEmployeeRVO.getPageSize());
        queryWrapper.ne(SQLConf.STATUS, EStatus.DISABLED);
        queryWrapper.orderByDesc(SQLConf.CREATE_TIME);
        IPage<UserEmployeeR> pageList = userEmployeeRService.page(page, queryWrapper);
        List<UserEmployeeR> list = pageList.getRecords();
        pageList.setRecords(list);
        return pageList;
    }

    @Override
    public List<UserEmployeeRVO> getUserEmployeeRByEmployeeCode(UserEmployeeRVO userEmployeeRVO) {
        return userEmployeeRMapper.getUserEmployeeRByEmployeeCode(userEmployeeRVO);
    }

    @Override
    public IPage<UserEmployeeRVO> getAllList(UserEmployeeRVO userEmployeeRVO) {
        Page<UserEmployeeR> page = new Page<>();
        page.setCurrent(1);
        page.setSize(userEmployeeRVO.getPageSize());
        IPage<UserEmployeeRVO> list = userEmployeeRMapper.allList(page, userEmployeeRVO);
        return list;
    }

    @Override
    public String add(UserEmployeeRVO userEmployeeRVO) {
        if (userEmployeeRVO.getStatus() == 3) {
            QueryWrapper<UserEmployeeR> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_uid", userEmployeeRVO.getUserUid());
            queryWrapper.eq("status", 3);
            if (userEmployeeRService.count(queryWrapper) > 0) {
                return ResultUtil.errorWithMessage("添加失败已经存在默认关注");
            }
        }
        //判重
        QueryWrapper<UserEmployeeR> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_uid", userEmployeeRVO.getUserUid());
        queryWrapper.eq("employee_uid", userEmployeeRVO.getEmployeeUid());
        queryWrapper.ne("status", EStatus.DISABLED);
        UserEmployeeR entity = userEmployeeRService.getOne(queryWrapper);
        if (entity == null) {
            entity = new UserEmployeeR();
            BeanUtils.copyProperties(userEmployeeRVO, entity, SysConf.STATUS);
            entity.insert();
        } else {
            userEmployeeRVO.setUid(entity.getUid());
            BeanUtils.copyProperties(userEmployeeRVO, entity);
            //entity.setUpdateTime//已通过填充实现，后续可删除(new Date());
            entity.updateById();
        }
        return ResultUtil.successWithMessage(MessageConf.INSERT_SUCCESS);
    }

    @Override
    public String edit(UserEmployeeRVO userEmployeeRVO) {
        UserEmployeeR entity = userEmployeeRService.getById(userEmployeeRVO.getUid());
        if (userEmployeeRVO.getStatus() == 3) {
            QueryWrapper<UserEmployeeR> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_uid", entity.getUserUid());
            queryWrapper.eq("status", 3);
            if (userEmployeeRService.count(queryWrapper) > 0) {
                return ResultUtil.errorWithMessage("请先修改已被选中的默认关注为正常状态再尝试");
            }
        }
        BeanUtils.copyProperties(userEmployeeRVO, entity);
        //entity.setUpdateTime//已通过填充实现，后续可删除(new Date());
        entity.updateById();
        return ResultUtil.successWithMessage(MessageConf.UPDATE_SUCCESS);
    }

    @Override
    public String delete(UserEmployeeRVO userEmployeeRVO) {
        UserEmployeeR entity = userEmployeeRService.getById(userEmployeeRVO.getUid());
        entity.setStatus(EStatus.DISABLED);
        //entity.setUpdateTime//已通过填充实现，后续可删除(new Date());
        entity.updateById();
        return ResultUtil.successWithMessage(MessageConf.UPDATE_SUCCESS);
    }

    @Override
    public String batchAdd(UserEmployeeRVO userEmployeeRVO) {
        String userUid = userEmployeeRVO.getUserUid();
        if (userUid == null) {
            return ResultUtil.errorWithMessage("获取当前用户信息错误稍后再试");
        } else {
            List<EmployeeVO> employeeList = userEmployeeRVO.getEmployeeList();
            if (employeeList.size() > 0) {
                int defaultSetCheck = 0;
                QueryWrapper<UserEmployeeR> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("user_uid", userUid);//request取出来
                queryWrapper.eq("status", 3);
                UserEmployeeR checkDefaultFollow = userEmployeeRService.getOne(queryWrapper);
                if (checkDefaultFollow != null) {
                    defaultSetCheck = 1;
                }
                for (EmployeeVO items : employeeList) {
                    queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("user_uid", userUid);//request取出来
                    queryWrapper.eq("employee_uid", items.getUid());
                    queryWrapper.ne("status", EStatus.DISABLED);
                    UserEmployeeR entity = userEmployeeRService.getOne(queryWrapper);
                    if (entity == null) {
                        entity = new UserEmployeeR();
                        entity.setUserUid(userUid);
                        entity.setEmployeeUid(items.getUid());
                        if (defaultSetCheck == 0) {
                            entity.setStatus(3);
                            defaultSetCheck = 1;
                        } else {
                            entity.setStatus(1);
                        }
                        entity.setType(1);//不明参数暂时放1处理
                        entity.setCreateTime(new Date());
                        entity.setCompanyUid(items.getCompanyUid());
                        entity.setEmployeeJsonData(JSONObject.toJSONString(items));
                        //entity.setUpdateTime//已通过填充实现，后续可删除(new Date());
                        entity.insert();
                    } else {
                        if (entity.getStatus() != 3) {
                            entity.setStatus(1);
                            //entity.setUpdateTime//已通过填充实现，后续可删除(new Date());
                            entity.setEmployeeJsonData(JSONObject.toJSONString(items));//重启后给新的值覆盖
                            entity.updateById();
                        }
                    }
                }
                return ResultUtil.successWithMessage("关注成功");
            } else {
                return ResultUtil.errorWithMessage("请先选择关注人");
            }
        }
    }

    @Override
    public UserEmployeeRVO selectFollowDetail(UserEmployeeRVO userEmployeeRVO) {
        UserEmployeeRVO resultVO = userEmployeeRMapper.selectFollowDetail(userEmployeeRVO);
        EmployeeVO employeeVO = JSONObject.parseObject(resultVO.getEmployeeJsonData(), EmployeeVO.class);
        resultVO.setCertCode(employeeVO.getCertCode());
        resultVO.setEmployeeName(employeeVO.getEmployeeName());
        resultVO.setEmployeeUid(employeeVO.getUid());
        resultVO.setDeptName(employeeVO.getDeptName());
        resultVO.setCompanyFullName(employeeVO.getCompanyFullName());
//        resultVO.setEmployeeJsonData(null);
        return resultVO;
    }

    @Override
    public boolean changeDefaultFollow(UserEmployeeRVO userEmployeeRVO) {
        QueryWrapper<UserEmployeeR> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_uid", userEmployeeRVO.getUserUid());
        queryWrapper.eq("employee_uid", userEmployeeRVO.getEmployeeUid());
        queryWrapper.ne("status", EStatus.DISABLED);
        UserEmployeeR userEmployeeR = userEmployeeRService.getOne(queryWrapper);
        userEmployeeR.setStatus(3);
//        userEmployeeR.setUpdateTime(new Date());
        return userEmployeeR.updateById();
    }

    @Override
    public UserEmployeeR getDefaultUserEmployeeRMes(String userUid) {
        QueryWrapper<UserEmployeeR> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_uid", userUid);
        queryWrapper.eq("status", 3);
        UserEmployeeR userEmployeeR = userEmployeeRService.getOne(queryWrapper);
        return userEmployeeR;
    }

    @Override
    public void loginGetDefaultFollow(UserEmployeeRVO userEmployeeRVO) {
        UserEmployeeR userEmployeeR = getDefaultUserEmployeeRMes(userEmployeeRVO.getUserUid());
        if (userEmployeeR != null) {
            userEmployeeRVO.setEmployeeUid(userEmployeeR.getEmployeeUid());
            UserEmployeeRVO resultVO = selectFollowDetail(userEmployeeRVO);
            redisUtil.delete(RedisConf.EMPLOYEE_INFO + RedisConf.SEGMENTATION + userEmployeeRVO.getUserUid());
            redisUtil.setEx(RedisConf.EMPLOYEE_INFO + RedisConf.SEGMENTATION + userEmployeeRVO.getUserUid(), JsonUtils.objectToJson(resultVO), 24, TimeUnit.HOURS);
        }
    }

    @Override
    public String selectAllPresentUserFollowList(UserEmployeeRVO userEmployeeRVO) {
        List<UserEmployeeRVO> list = userEmployeeRMapper.selectAllPresentUserFollowList(userEmployeeRVO);
        if (list != null && list.size() > 0) {
            for (UserEmployeeRVO items : list) {
                EmployeeVO employeeVO = JSONObject.parseObject(items.getEmployeeJsonData(), EmployeeVO.class);

                Employee employee = employeeService.getById(employeeVO.getUid());
                items.setCertCode(employeeVO.getCertCode());
                items.setEmployeeName(employeeVO.getEmployeeName());
                items.setEmployeeCode(employeeVO.getEmployeeCode());
                items.setEmployeeUid(employeeVO.getUid());
                items.setDeptName(employeeVO.getDeptName());
                items.setIsFacePayment(employeeVO.getIsFacePayment());//不明参数
                items.setCompanyFullName(employeeVO.getCompanyFullName());
//                items.setEmployeeJsonData(null);
            }
            return ResultUtil.successWithData(list);
        } else {
            return ResultUtil.successWithMessage("当前没有关注人");
        }
    }

//    @Override
//    public String getEmployeeInfoFromRedis() {
//        String resultStr = redisUtil.get(RedisConf.EMPLOYEE_INFO + RedisConf.SEGMENTATION + userService.getPresentUserUid());
//        return resultStr;
//    }

    @Override
    public String unFollowEmployee(UserEmployeeRVO userEmployeeRVO) {
        boolean check = false;
        QueryWrapper<UserEmployeeR> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_uid", userEmployeeRVO.getUserUid());
        queryWrapper.eq("employee_uid", userEmployeeRVO.getEmployeeUid());
        queryWrapper.ne("status", EStatus.DISABLED);
        UserEmployeeR userEmployeeR = userEmployeeRService.getOne(queryWrapper);
        if (userEmployeeR.getStatus() == 3) {
            check = true;
        }
        userEmployeeR.setStatus(0);
//        userEmployeeR.setUpdateTime(new Date());
        userEmployeeR.updateById();
        if (check) {
            queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_uid", userEmployeeRVO.getUserUid());
            queryWrapper.eq("status", EStatus.ENABLE);
            List<UserEmployeeR> resultList = userEmployeeRService.list(queryWrapper);
            if (resultList != null && resultList.size() > 0) {
                UserEmployeeR changeR = resultList.get(0);
                changeR.setStatus(3);
                changeR.updateById();
            }
        }
        return ResultUtil.successWithMessage("取消成功");
    }

    @Override
    @Transactional
    public String updateEmployeeInfoFormServer(List<ServerSyncEmployeeInfo> resourceList) {
        for (ServerSyncEmployeeInfo item : resourceList) {
            UpdateWrapper<UserEmployeeR> updateWrapper = new UpdateWrapper<>();
            updateWrapper.set("employee_json_data", item.getJsonData());
            updateWrapper.eq("company_uid", item.getCompanyUid());
            updateWrapper.eq("employee_uid", item.getEmployeeUid());
            updateWrapper.eq("status", 1);//只更新存在关联的取关的不更新
            userEmployeeRService.update(updateWrapper);
        }
        return ResultUtil.successWithMessage("完成处理");
    }

    @Override
    public List<UserEmployeeRVO> getByEmployeeUid(String employeeUid, int type) {
        return userEmployeeRMapper.getByEmployeeUid(employeeUid,type);
    }
}
